﻿using STHPMS1.Common.C_Entity;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Core;
using STHPMS1.ICore.I_UI;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using STHPMS1.Common.C_Extension;
using STHPMS1.Web.W_Model;
using System.Collections.Generic;
using Newtonsoft.Json;
using STHPMS1.Common.C_Utils;
using System.Data;
using System.Reflection;
using System.Linq.Expressions;
using System.Web.Caching;

namespace STHPMS1.Web.W_Controller.Decision.Needs
{
    [RoutePrefix("api/DiviResult")]
    public class DiviResultController : STHPMS1.Web.W_Core.MyController
    {

        [Route("")]
        public void Delete(Dn_Divi_Result entity)
        {
            this.Scene.Bll.Dn_Divi_Result.RemoveAll(entity);//删除养护路段和关联单元
        }

        [Route("clear")]
        public void PostDelete(string rdid,string m_w)
        {
            this.Scene.Bll.Dn_Divi_Result.Clear(rdid, m_w);
        }

        [Route("clearOther")]
        public void PostDeleteOther(string rdid, string m_w)
        {
            this.Scene.Bll.Dn_Divi_Result.ClearOther(rdid, m_w);
        }

        [Route("main")]
        public IHttpActionResult Get(string rdid = null)
        {
            var data = this.Scene.Bll.Dn_Divi_Result.GetMainNeedWay<Dn_Divi_Result>(rdid);
            if (data == null) return NotFound();
            return Ok(data);
        }

        [Route("")]
        [Route("page/{page?}", Name = "GetDiviResultByPage")]
        [Route("rows/{rows?}")]
        [Route("page/{page?}/rows/{rows?}")]
        public IHttpActionResult Get(string rdid = null,string m_w=null ,int page = 1, int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p > 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;
            //条件
          
            var data = this.Scene.Bll.Dn_Divi_Result.GetNewSegment<Dn_Divi_Result>(rdid,m_w, info);
            if (data == null) return NotFound();

            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }


        /// <summary>
        /// 拷贝一个养护路段对象
        /// </summary>
        /// <param name="old"></param>
        /// <returns></returns>
        private Dn_Divi_Result CopyObj(Dn_Divi_Result old)
        {
            Dn_Divi_Result newObj = new Dn_Divi_Result();
            newObj.Mainsegid = old.Mainsegid; //养护路段ID
            newObj.Beginmp = old.Beginmp;//起点桩号
            newObj.Endmp = old.Endmp;//结束桩号
            newObj.Segid = old.Segid;//原始路段ID
            newObj.Rdclass_Dictid = old.Rdclass_Dictid;//技术等级
            newObj.Segid_Main = old.Segid_Main;//养护类型
            newObj.Mainneed_Way = old.Mainneed_Way;//划分标准
            newObj.Divi_Time = old.Divi_Time;//划分时间
            newObj.Rdwayid = old.Rdwayid;//路线编号
            newObj.ModelGroup_PCI = old.ModelGroup_PCI;//PCI模型组
            //newObj.Mapobjectid = old.Mapobjectid;//路段地图标号
            newObj.Admdiv = old.Admdiv;//行政区域
            newObj.Manaut = old.Manaut;//管养单位
            //newObj.Fromloc = old.Fromloc;//起点位置
            //newObj.Toloc = old.Toloc;//终点位置
            newObj.Direction_Dictid = old.Direction_Dictid;//行车方向
            newObj.Numlanes = Convert.ToByte(old.Numlanes);//车道数
            //newObj.Surfwidth = old.Surfwidth;//路面宽度
            //newObj.Sltp_Dictid = old.Sltp_Dictid;//土基类型
            //newObj.Should_Dictid = old.Should_Dictid;//路肩类型
            //newObj.Median = old.Median;//中间分隔带
            //newObj.Shldwidth = old.Shldwidth;//路肩宽度
            //newObj.Comments = old.Comments;//备注
            //newObj.Lastmain_Year = old.Lastmain_Year;//最后大修
            newObj.Pvmttype_Dictid = old.Pvmttype_Dictid;//面层类型
            newObj.BeginDate = old.BeginDate;//通车时间
            return newObj;
        }

  
        /*
        /// <summary>
        /// 划分路段
        /// </summary>
        /// <param name="rdid">路线编号</param>
        /// <param name="gf">规范</param>
        /// <param name="zb">指标</param>
        /// <returns></returns>
        [Route("divide")]
        public HttpResponseMessage PostDivide(string rdid, string gf, string zb)
        {
            try
            {
                Dictionary<string, string[]> u_dn = new Dictionary<string, string[]>();//单元编号和养护路段编号的键值对
                //根据路线编号，查询路段
                List<B_Invntory> b_Invntorys = this.Scene.Bll.B_Invntory.GetList<B_Invntory>(rdid);
                if (b_Invntorys.Count == 0)
                {
                    var res = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent("当前路线下没有已知路段"),
                        ReasonPhrase = "Server Error"
                    };
                    throw new HttpResponseException(res);
                }
                List<Dn_Divi_Result> newList = new List<Dn_Divi_Result>();//保存养护划分路段


                //遍历路段
                foreach (B_Invntory b in b_Invntorys)
                {
                    int _RDCLASS_DICTID = Convert.ToInt32(b.Rdclass_Dictid);//技术等级
                    //创建一个养护路段
                    Dn_Divi_Result divi = new Dn_Divi_Result();
                    divi.Beginmp = b.Beginmp;//起点桩号

                    divi.Rdclass_Dictid = _RDCLASS_DICTID;//技术等级
                    divi.Segid = b.Segid;//原始路段编号
                    divi.Divi_Time = DateTime.Now.ToShortDateString();//划分时间
                    divi.Rdwayid = b.Rdwayid;//路段所属线路编号
                    divi.Mapobjectid = b.Mapobjectid;//路段地图标号
                    divi.Rd_Admdiv = b.Admdiv;//行政区域
                    divi.Manaut = b.Manaut;//管养单位
                    divi.Fromloc = b.Fromloc;//起点位置
                    divi.Toloc = b.Toloc;//终点位置
                    divi.Direction_Dictid = b.Direction_Dictid;//行车方向
                    divi.Numlanes = Convert.ToByte(b.Numlanes);//车道数
                    divi.Pvmttype_Dictid = b.Pvmttype_Dictid;//路面类型
                    divi.Surfwidth = b.Surfwidth;//路面宽度
                    divi.Sltp_Dictid = b.Sltp_Dictid;//土基类型
                    divi.Should_Dictid = b.Should_Dictid;//路肩类型
                    divi.Median = b.Median;//中间分隔带
                    divi.Shldwidth = b.Shldwidth;//路肩宽度
                    divi.Comments = b.Comments;//备注
                    divi.Lastmain_Year = b.Lastmain_Year;//最后大修时间

                    //根据路段编号查询相关单元编号
                    List<string> units = this.Scene.Bll.B_Invntory_Unit.GetUnit(b.Segid);
                    List<int> yhList = new List<int>();//保存检查单元的养护类型
                    List<string> unitIdList = new List<string>();//单元编号

                    List<string> gs = GetGS(gf, _RDCLASS_DICTID, Convert.ToInt32( zb));//返回路段的计算公式(多个)
                    //遍历单元编号
                    foreach (string u in units)
                    {
                        //获取单元对象
                        B_Unit unit = this.Scene.Bll.B_Unit.GetSingle<B_Unit>(u);

                        //获取单元的评定指标对象
                        E_Roadwaydetail e = this.Scene.Bll.E_Roadwaydetail.GetSingle<E_Roadwaydetail>(u, rdid, b.Direction_Dictid);
                        if (e != null)
                        {
                            //得到当前单元的养护类型
                            //int yhtemp = GetYH(_RDCLASS_DICTID, e, gf, Convert.ToInt32(zb));
                            int yhtemp = GetYH(gs, Convert.ToInt32(zb), e);
                            if (yhList.Count > 0) //判断是否存在第一个单元的养护类型
                            {
                                if (yhList.Contains(yhtemp) || yhtemp == -1) //当前单元养护类型和上次的单元养护类型比较
                                {

                                    divi.Endmp = unit.Endmp; //移动养护路段的结束桩号
                                }
                                else //不同养护类型
                                {
                                    //保存养护路段编号和单元对应
                                    string[] unitArrays = new string[unitIdList.Count];
                                    unitIdList.CopyTo(unitArrays);
                                    u_dn.Add(divi.Mainsegid, unitArrays);
                                    unitIdList.Clear();

                                    divi.Segid_Main = yhList[0];//上次的养护类型
                                    //将上次的养护路段添加到集合
                                    newList.Add(CopyObj(divi));

                                    yhList.Clear(); //清空养护类型的集合,为下次准备
                                    unitIdList.Clear();//清空单元编号集合,为下次准备
                                    yhList.Add(yhtemp);
                                    //创建新的养护路段(编号和起始桩号,养护类型)
                                    //divi.Mainsegid = "YH" + b.Segid + "_" + yhtemp + "_" + DateTime.Now.ToString("yyyyMMss");//养护路段编号
                                    divi.Mainsegid = "YH_" + Guid.NewGuid().ToString();
                                    divi.Beginmp = unit.Beginmp;//起点桩号
                                    divi.Endmp = unit.Endmp;//结束桩号
                                    divi.Segid_Main = yhtemp;//养护类型

                                }
                                unitIdList.Add(u);//添加单元编号
                            }
                            else //初次读取单元此类型
                            {
                                yhList.Add(yhtemp);//初始化养护类型
                                //divi.Mainsegid = "YH" + b.Segid + "_" + yhtemp + "_" + Guid.NewGuid().ToString();//养护路段编号
                                divi.Mainsegid = "YH_" + Guid.NewGuid().ToString();
                                divi.Endmp = unit.Endmp;
                                unitIdList.Add(u);//添加单元编号
                            }
                            //判断是否到终点单元
                            if (unit.Endmp == b.Endmp)
                            {
                                //unitIdList.Add(u);//添加单元编号
                                string[] unitArrays = new string[unitIdList.Count];
                                unitIdList.CopyTo(unitArrays);
                                u_dn.Add(divi.Mainsegid, unitArrays);
                                unitIdList.Clear();//清空单元编号集合

                                divi.Segid_Main = yhList[0];//最后的养护类型
                                //新的养护路段添加到集合
                                newList.Add(divi);
                                //清空List,并初始化
                                yhList.Clear();
                            }
                        }
                        else
                        {
                            continue;//如果此单元没有指标，跳过循环
                        }
                    }
                }

                List<B_Invntory_Unit> b_i_u_List = new List<B_Invntory_Unit>();//养护路段和关联单元
                foreach (KeyValuePair<string, string[]> kv in u_dn)
                {
                    foreach (string dy in kv.Value)
                    {
                        B_Invntory_Unit b_i_u = new B_Invntory_Unit()
                        {
                            Relatedid = Guid.NewGuid().ToString(),
                            Segid = kv.Key,
                            Unit = dy,
                            Rdwayid = rdid
                        };
                        b_i_u_List.Add(b_i_u);
                    }
                }


                //保存养护路段和单元关联
                this.Scene.Bll.Dn_Divi_Result.SaveAll(newList.ToArray(), b_i_u_List.ToArray());
            }
            catch (Exception ex)
            {
                var res = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(ex.Message),
                    ReasonPhrase = "Server Error"
                };
                throw new HttpResponseException(res);
            }

            var response = Request.CreateResponse(HttpStatusCode.Created);
            // Generate a link to the new book and set the Location header in the response.
            string uri = Url.Link("GetDiviResultByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }




        /// <summary>
        /// 返回养护类型
        /// </summary>
        /// <param name="gs">路段公式</param>
        /// <param name="zb">指标</param>
        /// <param name="e">单元计算数据</param>
        /// <returns></returns>
        private int GetYH(List<string> gs,int zb,E_Roadwaydetail e)
        {
            foreach (string temp in gs)
            {

                string[] tempGS = temp.Split(':'); //将公式和养护类型分割

                if (zb == 13000) //采用PSSI和PCI
                {
                    if (tempGS[0].Contains("a"))
                    {
                        tempGS[0] = tempGS[0].Replace("a", e.Pssi.ToString());
                    }
                    if (tempGS[0].Contains("b"))
                    {
                        tempGS[0] = tempGS[0].Replace("b", e.Pci.ToString());
                    }
                   if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                     {
                         return Convert.ToInt32( tempGS[1]);
                     }
                }
                else if (zb == 13001) //采用RQI
                {
                   
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0].Replace("a", e.Rqi.ToString())))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 13002) //采用SRI
                {
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0].Replace("a", e.Sri.ToString())))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                if (zb == 14000) //采用PCI
                {
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0].Replace("a", e.Pci.ToString())))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 14001) //采用PQI和PCI
                {
                    if (tempGS[0].Contains("a"))
                    {
                        tempGS[0] = tempGS[0].Replace("a", e.Pqi.ToString());
                    }
                    if (tempGS[0].Contains("b"))
                    {
                        tempGS[0] = tempGS[0].Replace("b", e.Pci.ToString());
                    }
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 14002) //采用PCI和PSSI
                {
                    if (tempGS[0].Contains("a"))
                    {
                        tempGS[0] = tempGS[0].Replace("a", e.Pssi.ToString());
                    }
                    if (tempGS[0].Contains("b"))
                    {
                        tempGS[0] = tempGS[0].Replace("b", e.Pci.ToString());
                    }
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }

            }
            
            return -1;
        }

      

        /// <summary>
        /// 返回单元的养护类型
        /// </summary>
        /// <param name="js">技术等级</param>
        /// <param name="e">单元评价数据</param>
        /// <param name="gf">规范</param>
        /// <param name="zb">评价指标</param>
        /// <returns></returns>
        private int GetYH(int js, E_Roadwaydetail e, string gf, int zb)
        {
            if (js >= 162)
            { js = 162; } //二级公路
            else
            { js = 160; } //一级以上公路
            string gs = "";
            //根据规范提取公式
            if (gf == "0") //国家规范
            {
                List<Dn_Stand_Wan> stand = this.Scene.Bll.Dn_Stand_Wan.GetList<Dn_Stand_Wan>(zb, js);
                foreach (Dn_Stand_Wan s in stand)
                {
                    if (zb == 13000) //采用PSSI和PCI
                    {
                        gs = s.Standsql.Replace("a", e.Pssi.ToString()).Replace("b", e.Pci.ToString());//公式

                    }
                    else if (zb == 13001) //采用RQI
                    {
                        gs = s.Standsql.Replace("a", e.Rqi.ToString());//公式
                    }
                    else if (zb == 13002) //采用SRI
                    {
                        gs = s.Standsql.Replace("a", e.Sri.ToString());//公式
                    }
                    if (Common.C_Utils.Evaluator.EvaluateToBool(gs))//公式执行
                    {
                        return Convert.ToInt32(s.Main_Type);
                    }
                }
            }
            else if (gf == "1")//华美规范
            {
                List<Dn_Huamei_Way> hm = this.Scene.Bll.Dn_Huamei_Way.GetList<Dn_Huamei_Way>(zb, js);
                foreach (Dn_Huamei_Way s in hm)
                {
                    if (zb == 14000) //采用PCI
                    {
                        gs = s.Standsql.Replace("a", e.Pci.ToString());//公式

                    }
                    else if (zb == 14001) //采用PQI和PCI
                    {
                        gs = s.Standsql.Replace("a", e.Pqi.ToString()).Replace("b", e.Pci.ToString());//公式
                    }
                    else if (zb == 14002) //采用PCI和PSSI
                    {
                        gs = s.Standsql.Replace("a", e.Pssi.ToString()).Replace("b", e.Pci.ToString());//公式
                    }
                    //还有两种
                    if (Common.C_Utils.Evaluator.EvaluateToBool(gs))//公式执行
                    {
                        return Convert.ToInt32(s.Main_Type);
                    }
                }
            }
            return -1;
        }

        */


        [Route("divide_test")]
        public HttpResponseMessage PostDivideTest(string rdid, string gf, string zb)
        {
            try
            {
                string time = DateTime.Now.ToString("yyyyMMddHHmmss");//时间戳
                string timeDivide = DateTime.Now.ToShortDateString();//划分时间
                Dictionary<string, string[]> u_dn = new Dictionary<string, string[]>();//单元编号和养护路段编号的键值对
                //根据路线编号，查询路段
                List<B_Invntory> b_Invntorys = this.Scene.Bll.B_Invntory.GetList<B_Invntory>(rdid);
                if (b_Invntorys.Count == 0)
                {
                    var res = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent("当前路线下没有已知路段"),
                        ReasonPhrase = "Server Error"
                    };
                    throw new HttpResponseException(res);
                }
                List<Dn_Divi_Result> newList = new List<Dn_Divi_Result>();//保存养护划分路段


                //遍历路段
                foreach (B_Invntory b in b_Invntorys)
                {
                    int _RDCLASS_DICTID = Convert.ToInt32(b.Rdclass_Dictid);//技术等级
                    //创建一个养护路段
                    Dn_Divi_Result divi = new Dn_Divi_Result();
                    divi.Beginmp = b.Beginmp;//起点桩号
                    divi.Endmp = b.Endmp;//终点桩号
                    divi.Rdclass_Dictid = _RDCLASS_DICTID;//技术等级
                    divi.Segid = b.Segid;//原始路段编号
                    divi.Divi_Time = time;//划分时间
                    divi.Rdwayid = b.Rdwayid;//路段所属线路编号
                    //divi.Mapobjectid = b.Mapobjectid;//路段地图标号
                    divi.Admdiv = b.Admdiv;//行政区域
                    divi.Manaut = b.Manaut;//管养单位
                    //divi.Fromloc = b.Fromloc;//起点位置
                    //divi.Toloc = b.Toloc;//终点位置
                    divi.Direction_Dictid = b.Direction_Dictid;//行车方向
                    divi.Numlanes = Convert.ToByte(b.Numlanes);//车道数
                    divi.Pvmttype_Dictid = b.Pvmttype_Dictid;//面层类型
                    divi.ModelGroup_PCI = b.Modelgroup_Pci;//PCI模型组
                    //divi.Surfwidth = b.Surfwidth;//路面宽度
                    //divi.Sltp_Dictid = b.Sltp_Dictid;//土基类型
                    //divi.Should_Dictid = b.Should_Dictid;//路肩类型
                    //divi.Median = b.Median;//中间分隔带
                    //divi.Shldwidth = b.Shldwidth;//路肩宽度
                    //divi.Comments = b.Comments;//备注
                    divi.Mainneed_Way = gf + "_" + zb;//养护需求分析方法

                    List<int> yhList = new List<int>();//保存检查单元的养护类型
                    List<string> unitIdList = new List<string>();//单元编号

                    List<string> gs = GetGS(gf, _RDCLASS_DICTID, Convert.ToInt32(zb));//返回路段的计算公式(多个)

                    //查询该路段的单元明细和单元评定指标
                    DataTable dt = this.Scene.Bll.B_Unit.GetUnitZB(b.Segid);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("该路段缺少检查数据，无法划分,起终桩号为:" + b.Beginmp+"--"+b.Endmp);
                        //divi.Mainsegid = GetSegID(divi.Beginmp, rdid, divi.Direction_Dictid, time);//养护路段编号
                        //divi.Comments = "缺少检测数据,未能划分";
                        ////*****************************************是否保存对应单元?
                        //newList.Add(divi);
                    }
                    //遍历单元(包含起始桩号和各个评定数据)
                    foreach (DataRow  row in dt.Rows)
                    {
                            //得到当前单元的养护类型
                            //int yhtemp = GetYH(_RDCLASS_DICTID, e, gf, Convert.ToInt32(zb));
                            int yhtemp = GetYH(gs,  row);
                            if (yhList.Count > 0) //判断是否存在第一个单元的养护类型
                            {
                                if (yhList.Contains(yhtemp) || yhtemp == -1) //当前单元养护类型和上次的单元养护类型比较
                                {

                                    divi.Endmp = Convert.ToDouble( row["ENDMP"]); //移动养护路段的结束桩号
                                }
                                else //不同养护类型
                                {
                                    //保存养护路段编号和单元对应
                                    string[] unitArrays = new string[unitIdList.Count];
                                    unitIdList.CopyTo(unitArrays);
                                    u_dn.Add(divi.Mainsegid, unitArrays);
                                    unitIdList.Clear();

                                    divi.Segid_Main = yhList[0];//上次的养护类型
                                    //将上次的养护路段添加到集合
                                    newList.Add(CopyObj(divi));

                                    yhList.Clear(); //清空养护类型的集合,为下次准备
                                    unitIdList.Clear();//清空单元编号集合,为下次准备
                                    yhList.Add(yhtemp);
                                    //创建新的养护路段(编号和起始桩号,养护类型)

                                    double? beginmp = Convert.ToDouble(row["BEGINMP"]);//起始桩号
                                    divi.Mainsegid = GetSegID(beginmp, rdid, divi.Direction_Dictid,time);//养护路段编号
                                    //divi.Mainsegid = "YH_" + Guid.NewGuid().ToString();
                                    divi.Beginmp = beginmp;//起点桩号
                                    divi.Endmp = Convert.ToDouble(row["ENDMP"]);//结束桩号
                                    divi.Segid_Main = yhtemp;//养护类型

                                }
                                unitIdList.Add(row["UNIT"].ToString());//添加单元编号
                            }
                            else //初次读取单元此类型
                            {
                                yhList.Add(yhtemp);//初始化养护类型
                                divi.Mainsegid = GetSegID(divi.Beginmp,rdid,divi.Direction_Dictid,time);//养护路段编号
                                //divi.Mainsegid = "YH_" + Guid.NewGuid().ToString();
                                divi.Endmp = Convert.ToDouble(row["ENDMP"]);
                                unitIdList.Add(row["UNIT"].ToString());//添加单元编号
                            }
                            //判断是否到终点单元
                            if (Convert.ToDouble(row["ENDMP"]) == b.Endmp)
                            {
                                //unitIdList.Add(u);//添加单元编号
                                string[] unitArrays = new string[unitIdList.Count];
                                unitIdList.CopyTo(unitArrays);
                                u_dn.Add(divi.Mainsegid, unitArrays);
                                unitIdList.Clear();//清空单元编号集合

                                divi.Segid_Main = yhList[0];//最后的养护类型
                                //新的养护路段添加到集合
                                newList.Add(divi);
                                //清空List,并初始化
                                yhList.Clear();
                            }
                        }
                    }

                List<B_Invntory_Unit> b_i_u_List = new List<B_Invntory_Unit>();//养护路段和关联单元
                foreach (KeyValuePair<string, string[]> kv in u_dn)
                {
                    foreach (string dy in kv.Value)
                    {
                        B_Invntory_Unit b_i_u = new B_Invntory_Unit()
                        {
                            Relatedid = Guid.NewGuid().ToString(),
                            Segid = kv.Key,
                            Unit = dy,
                            Rdwayid = rdid
                        };
                        b_i_u_List.Add(b_i_u);
                    }
                }

                //删除相同路线相同划分方式的养护路段和单元关联
                this.Scene.Bll.Dn_Divi_Result.Clear(rdid, gf + "_" + zb);
                //保存养护路段和单元关联
                this.Scene.Bll.Dn_Divi_Result.SaveAll(newList.ToArray(), b_i_u_List.ToArray());
                newList.Clear();
                b_i_u_List.Clear();
            }
            catch (Exception ex)
            {
                var res = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(ex.Message),
                    ReasonPhrase = "Server Error"
                };
                throw new HttpResponseException(res);
            }

            var response = Request.CreateResponse(HttpStatusCode.Created);
            // Generate a link to the new book and set the Location header in the response.
            string uri = Url.Link("GetDiviResultByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }


        //返回路段的计算公式
        private List<string> GetGS(string gf, int js, int zb)
        {
            if (Common.C_Definition.MyCacheTools.IsCacheExist(gf + "_" + js + "_" + zb))
            {
                return (List<string>)Common.C_Definition.MyCacheTools.GetCache(gf + "_" + js + "_" + zb);
            }
            else
            {
                List<string> gs = new List<string>();
                if (js >= Common.C_Enum.RoadClassEnum.R162.GetEnumValue() ) { js = 162; } //二级公路
                else { js = 160; } //一级以上公路

                if (gf == "0") //国家规范
                {
                    List<Dn_Stand_Wan> stand = this.Scene.Bll.Dn_Stand_Wan.GetList<Dn_Stand_Wan>(zb, js);
                    foreach (Dn_Stand_Wan s in stand)
                    {
                        gs.Add(s.Standsql + ":" + s.Main_Type); //公式和养护类型对应
                    }

                }
                else //华美规范
                {
                    List<Dn_Huamei_Way> hm = this.Scene.Bll.Dn_Huamei_Way.GetList<Dn_Huamei_Way>(zb, js);
                    foreach (Dn_Huamei_Way s in hm)
                    {
                        gs.Add(s.Standsql + ":" + s.Main_Type); //公式和养护类型对应
                    }
                }
                //公式放到缓存
                Common.C_Definition.MyCacheTools.SetCache(gf + "_" + js + "_" + zb, gs, 5);
                return gs;
            }
        }

        /// <summary>
        /// 返回养护类型
        /// </summary>
        /// <param name="gs">路段公式</param>
        /// <param name="zb">指标</param>
        /// <param name="row">单元计算数据</param>
        /// <returns></returns>
        private int GetYH(List<string> gs, DataRow row)
        {
            foreach (string temp in gs)
            {
                string[] tempGS = temp.Split(':'); //将公式和养护类型分割
                if (tempGS[0].Contains("PCI"))
                {
                    if (row["PCI"] == null || row["PCI"].ToString()=="") throw new Exception("缺少PCI数据，无法根据此选项划分路段");
                    tempGS[0] = tempGS[0].Replace("PCI", row["PCI"].ToString());
                }
                if (tempGS[0].Contains("PSSI"))
                {
                    if (row["PSSI"] == null || row["PSSI"].ToString() == "") throw new Exception("缺少PSSI数据，无法根据此选项划分路段");
                    tempGS[0] = tempGS[0].Replace("PSSI",row["PSSI"].ToString());
                }
                if (tempGS[0].Contains("RQI"))
                {
                    if (row["RQI"] == null || row["RQI"].ToString() == "") throw new Exception("缺少RQI数据，无法根据此选项划分路段");
                    tempGS[0] = tempGS[0].Replace("RQI", row["RQI"].ToString());
                }
                if (tempGS[0].Contains("PQI"))
                {
                    if (row["PQI"] == null || row["PQI"].ToString() == "") throw new Exception("缺少PQI数据，无法根据此选项划分路段");
                    tempGS[0] = tempGS[0].Replace("PQI", row["PQI"].ToString());
                }
                if (tempGS[0].Contains("SRI"))
                {
                    if (row["SRI"] == null || row["SRI"].ToString() == "") throw new Exception("缺少SRI数据，无法根据此选项划分路段");
                    tempGS[0] = tempGS[0].Replace("SRI", row["SRI"].ToString());
                }
                if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                {
                    return Convert.ToInt32(tempGS[1]);
                }
                /*

                if (zb == 13000) //采用PSSI和PCI
                {
                    if (tempGS[0].Contains("a"))
                    {
                        tempGS[0] = tempGS[0].Replace("a", row["PSSI"] == null ? "0" : row["PSSI"].ToString());
                    }
                    if (tempGS[0].Contains("b"))
                    {
                        tempGS[0] = tempGS[0].Replace("b", row["PCI"] == null ? "0" : row["PCI"].ToString());
                    }
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 13001) //采用RQI
                {

                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0].Replace("a", row["RQI"] == null ? "0" : row["RQI"].ToString())))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 13002) //采用SRI
                {
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0].Replace("a", row["SRI"] == null ? "0" : row["SRI"].ToString())))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                if (zb == 14000) //采用PCI
                {
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0].Replace("a", row["PCI"] == null ? "0" : row["PCI"].ToString())))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 14001) //采用PQI和PCI
                {
                    if (tempGS[0].Contains("a"))
                    {
                        tempGS[0] = tempGS[0].Replace("a", row["RQI"] == null ? "0" : row["RQI"].ToString());
                    }
                    if (tempGS[0].Contains("b"))
                    {
                        tempGS[0] = tempGS[0].Replace("b", row["PCI"] == null ? "0" : row["PCI"].ToString());
                    }
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                else if (zb == 14002) //采用PCI和PSSI
                {
                    if (tempGS[0].Contains("a"))
                    {
                        tempGS[0] = tempGS[0].Replace("a", row["PSSI"] == null ? "0" : row["PSSI"].ToString());
                    }
                    if (tempGS[0].Contains("b"))
                    {
                        tempGS[0] = tempGS[0].Replace("b", row["PCI"] == null ? "0" : row["PCI"].ToString());
                    }
                    if (Common.C_Utils.Evaluator.EvaluateToBool(tempGS[0]))//公式执行
                    {
                        return Convert.ToInt32(tempGS[1]);
                    }
                }
                */
            }
            return -1;
        }


        /// <summary>
        /// 返回养护路段编号
        /// </summary>
        /// <param name="beginmp">起始桩号</param>
        /// <param name="rdid">路线编号</param>
        /// <param name="dir">方向</param>
        /// <param name="dir">时间戳</param>
        /// <returns></returns>
        private string GetSegID(double? beginmp,string rdid,int? dir,string time)
        {
            string dirStr = "All";
            if(dir==Common.C_Enum.DirectionEnum.Up11.GetEnumValue())
            {
                dirStr = "Up";
            }
            else if(dir==Common.C_Enum.DirectionEnum.Down12.GetEnumValue())
            {
                dirStr = "Down";
            }
            return "YLD_" + rdid + "_" + beginmp + "_" + dirStr + "_" + time;
        }
    }
}